package cn.maihe.elg.operation.supports.electronicseal.anne;

import cn.maihe.elg.operation.config.AnneSignConfig;
import cn.maihe.elg.operation.config.ElgConfig;
import cn.maihe.elg.operation.model.enums.AuditStatusEnum;
import cn.maihe.elg.operation.model.enums.BidCustomerStatus;
import cn.maihe.elg.operation.model.enums.ContractStatus;
import cn.maihe.elg.operation.repository.entity.*;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.account.IndividualRealNameSyncRequestBody;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.contract.ContractDetailListResponse;
import cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.enterprise.vo.EnterpriseResult;
import cn.maihe.elg.operation.supports.electronicseal.anne.service.impl.*;
import cn.maihe.framework.starter.mybatis.dao.MybatisDaoImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.nio.file.Path;
import java.util.List;

/**
 * 安妮电签
 */
@Service
@Slf4j
public class AnneSignService {

    private ElgConfig elgConfig;


    @Resource
    private BidCustomerService bidCustomerService;

    @Resource
    private EnterpriseCreateService enterpriseCreateService;
    @Resource
    private EnterpriseResultQueryService enterpriseResultQueryService;
    @Resource
    private ContractCreateService contractCreateService;
    @Resource
    private ContractStartSignService contractStartSignService;
    @Resource
    private ContractAutoSignService contractAutoSignService;
    @Resource
    private ContractDownloadService contractDownloadService;
    @Resource
    private ContractDetailListService contractDetailListService;
    @Resource
    private ContractPreViewService contractPreViewService;
    @Resource
    private IndividualRealNameSyncService individualRealNameSyncService;


    public AnneSignService(AnneSignConfig anneSignConfig, ElgConfig elgConfig) {
        this.elgConfig = elgConfig;
//        Assert.notEmpty(anneSignConfig.getTemplateMap(), "参数[cn.maihe.elg.anne.template-map]安妮相关合同模板未配置");
      }


    /**
     * 开立保函申请委托书
     *
     * @param orderInfo 投标申请订单信息
     */
    public Long createGuaranteeDelegateProtocol(AcceptOrderInfoDO orderInfo) {
        return contractCreateService.createGuaranteeDelegateProtocol(orderInfo);
    }

    /**
     * 担保保函书 创建
     * channelContractId
     *
     * @param orderInfo 投标申请订单信息
     */
    public AcceptOrderContract createGuaranteeContract(ApplyOrderInfoDO orderInfo) {
        return contractCreateService.createGuaranteeContract(orderInfo);
    }

    /**
     *  到账证明 创建
     * channelContractId
     *
     * @param orderInfo 投标申请订单信息
     */
    public AcceptOrderContract createReceiveContract(ApplyOrderInfoDO orderInfo) {
        return contractCreateService.createReceiveContract(orderInfo);
    }


    public Long realNameSync(IndividualRealNameSyncRequestBody body) {
        return individualRealNameSyncService.realNameSync(body);
    }


    /**
     * 发起合同签署
     * 创建合同-发起合同签署-自动合同签署|手动签署
     *
     * @param anneSignContractId
     */
    public void startSign(Long anneSignContractId) {
        contractStartSignService.startSign(anneSignContractId);
    }

    /**
     * 创建合同-发起合同签署-自动合同签署|手动签署
     */
    public void autoSign(Long anneSignContractId) {
        contractAutoSignService.autoSign(anneSignContractId);
    }


    /**
     * 合同详情  todo 待整合到 查询合同详情合同状态处理
     *
     * @param anneSignContractId
     */
    public ContractDetailListResponse getContractDetail(Long anneSignContractId) {
        return contractDetailListService.getContractDetail(anneSignContractId);
    }
    public ContractStatus getContractStatusByDetail(Long anneSignContractId) {
        ContractDetailListResponse response = contractDetailListService.getContractDetail(anneSignContractId);
        String status = response.getBody().getContractDetailList().get(0).getInfoVo().getStatus();
        return ContractStatus.valueOf(status);
    }

    /**
     * 合同预览
     *
     * @param anneSignContractId
     */
    public List<String> contractPreview(Long anneSignContractId) {
        return contractPreViewService.contractPreview(anneSignContractId);
    }

    /**
     * 合同下载
     *
     * @param anneSignContractId
     * @return
     */
    public Path downloadContract(Long anneSignContractId) {
        return contractDownloadService.downloadContract(anneSignContractId);
    }
    /**
     * 合同下载
     *
     * @param anneSignContractId
     * @return
     */
    public Path downloadContract(Long anneSignContractId,String acceptOrderNo) {
        return contractDownloadService.downloadContract(anneSignContractId,acceptOrderNo);
    }

    /**
     * 安妮渠道 创建投标企业
     */
    public void createEnterprise4BidCustomer(Long bidCustomerId,String auditDesc, String legalPersonTel) {
        enterpriseCreateService.createBidderEnterprise(bidCustomerId, auditDesc, legalPersonTel);
    }

    /**
     * 安妮渠道创建担保机构企业
     *
     * @param organization
     */
    public void createEnterprise4Org(OrganizationDO organization) {
        enterpriseCreateService.createOrgEnterprise(organization);
    }


    /**
     * 查询企业审核结果
     *
     * @param bidCustomerId 投标客户ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void queryEnterprise4BidCustomer(Long bidCustomerId) {
        BidCustomerDO bidCustomerDO = MybatisDaoImpl.run().selectById(BidCustomerDO.class, bidCustomerId);
        Assert.notNull(bidCustomerDO, "查无此投标客户信息");
        if (BidCustomerStatus.AUDIT_OUTER.getStatus() != bidCustomerDO.getStatus()) {
            log.warn("投标客户非待第三方审核状态，无需发起企业创建结果查询");
            return;
        }
        Assert.hasText(bidCustomerDO.getBidderCreditCode(), "18位的统一社会信用代码不能为空");

        EnterpriseResult result = enterpriseResultQueryService.queryEnterpriseResult(bidCustomerDO.getBidderCreditCode());
        if (result != null) {
            Long enterpriseId = result.getEnterpriseId();
            String auditOpinion = result.getAuditDesc();
            bidCustomerDO.setAuditDesc(auditOpinion);
            bidCustomerDO.setResultQueryTimes(bidCustomerDO.getResultQueryTimes() + 1);

            if (result.getStatus() == EnterpriseStatus.AUDIT_PASS) {
                bidCustomerDO.setStatus(BidCustomerStatus.NORMAL.getStatus());
                bidCustomerDO.setEnterpriseId(enterpriseId);
                bidCustomerService.customerSuccess(bidCustomerDO);
            } else if (result.getStatus() == EnterpriseStatus.AUDIT_REJECT) {
                bidCustomerDO.setStatus(BidCustomerStatus.AUDIT_FAIL.getStatus());
            }
            bidCustomerService.updateById(bidCustomerDO);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void queryEnterprise4org(Long orgId) {
        OrganizationDO organizationDO = MybatisDaoImpl.run().selectById(OrganizationDO.class, orgId);
        Assert.notNull(organizationDO, "查无此担保机构信息");

        if (AuditStatusEnum.AUDIT_OUT.getValue() != organizationDO.getAuditStatus()) {
            log.warn("担保机构非待第三方审核状态，无需发起企业创建结果查询");
            return;
        }
        Assert.hasText(organizationDO.getCreditCode(), "18位的统一社会信用代码不能为空");

        EnterpriseResult result = enterpriseResultQueryService.queryEnterpriseResult(organizationDO.getCreditCode());
        if (result != null) {
            Long enterpriseId = result.getEnterpriseId();
            String auditOpinion = result.getAuditDesc();
            organizationDO.setAuditDesc(auditOpinion);
            organizationDO.setResultQueryTimes(organizationDO.getResultQueryTimes() + 1);

            if (result.getStatus() == EnterpriseStatus.AUDIT_PASS) {
                organizationDO.setAuditStatus(AuditStatusEnum.AUDITED.getValue());
                organizationDO.setEnterpriseId(enterpriseId);
                organizationDO.setBusinessStatus(1);
            } else if (result.getStatus() == EnterpriseStatus.AUDIT_REJECT) {
                organizationDO.setAuditStatus(AuditStatusEnum.AUDIT_REJECT.getValue());
                organizationDO.setBusinessStatus(0);
            }
            MybatisDaoImpl.run().updateById(organizationDO);
        }

    }


}
